/**
 * 需求简历，列表页
 */
import React from 'react';
import moment from 'moment';
import { router, withRouter } from 'umi';
import { Input, Radio, Button, Form, Icon, DatePicker, Select, Spin } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import { Pagination } from '@/components';
import { getDict } from '@/utils/dataDictUtil';
import { eventTrack } from '@/utils/track';

import { isEqual } from 'lodash';
import styles from './List.less';
import { SEX, LAST_POST_STATUS, READ_FLAG, CHANNEL_CONDITION_FLAG_ENUM } from '../dictionary';
import { ResumeCommonTable, ResumeCardTable } from '../containers';
import { CustomSearch } from '../components';
import { queryResumeList, queryTagList } from '../service';

const toNumber = val => {
    if (val instanceof Array) {
        return val.map(toNumber);
    }
    return !val && val !== 0 ? undefined : Number(val);
};
const NUMBER_KEYS = ['pageNo', 'pageSize', 'lastPostStatus', 'readFlag', 'status'];
const STRING_ARR_KEYS = ['industryTypeList', 'workYearTypeList'];
const NUM_ARR_KEYS = ['recruitTagConfigIdList'];
function ResumeList({
    form,
    location,
    recruitCode,
    onDataExchange,
    isPrincipal,
    isLauncher,
    channelDict,
    recruitDetail
}) {
    const { query } = location;
    const { getFieldDecorator } = form;
    const [agreeTypeList, setAgreeTypeList] = React.useState([]); // 学历
    const [timeEmployedTypeList, setTimeEmployedTypeList] = React.useState([]); // 工作年限
    const [industryTypeDict, setIndustryTypeDict] = React.useState([]); // 行业背景
    const { data: tagList, loading: tagLoading } = useRequest(queryTagList, {
        refreshDeps: [],
        ...defaultFormatResult
    });

    // 字典获取
    React.useEffect(() => {
        getDict('agreeType').then(ret => setAgreeTypeList(ret));
        getDict('timeEmployedType').then(ret => setTimeEmployedTypeList(ret));
        getDict('industryType').then(ret => setIndustryTypeDict(ret));
    }, []);

    // 查询逻辑
    // 初始化： query(无需转换的 + specialQuery) => condition => queryList
    // 条件变化:  set query => 初始化逻辑
    const {
        startApplyTime,
        endApplyTime,
        talentName,
        name,
        lastPost,
        talentSex,
        talentDegree,
        lastCompany,
        talentGraduateSchool,
        talentProfession,
        notesSourceList // 渠道标识
    } = query;
    const nextNotesSourceList = React.useMemo(() => {
        const rckValue = channelDict.find(channel => channel.text === '人才库')?.value;
        // 特殊场景 只查人才库
        if (notesSourceList === CHANNEL_CONDITION_FLAG_ENUM.RCK) {
            return [rckValue];
        }
        // 特殊场景 查人才库之外的所有渠道
        if (notesSourceList === CHANNEL_CONDITION_FLAG_ENUM.EXCLUDE_RCK) {
            return channelDict.filter(channel => channel.value !== rckValue).map(channel => channel.value);
        }
        if (notesSourceList instanceof Array) {
            return notesSourceList;
        }
        return notesSourceList ? [notesSourceList] : [];
    }, [channelDict, notesSourceList]);
    // 需转换成数字、字符串数组、数字数组
    const specialQuery = React.useMemo(
        () => ({
            notesSourceList: nextNotesSourceList,
            ...NUMBER_KEYS.reduce((pre, key) => ({ ...pre, [key]: toNumber(query[key]) }), {}),
            ...STRING_ARR_KEYS.reduce((pre, key) => {
                let next = query[key];
                if (!(next instanceof Array)) {
                    next = next ? [next] : [];
                }
                return { ...pre, [key]: next };
            }, {}),
            ...NUM_ARR_KEYS.reduce((pre, key) => {
                let next = query[key];
                if (next instanceof Array) {
                    next = next.map(toNumber);
                } else {
                    next = next ? [toNumber(next)] : [];
                }
                return { ...pre, [key]: next };
            }, {})
        }),
        [...[...NUMBER_KEYS, ...NUM_ARR_KEYS, ...STRING_ARR_KEYS].map(item => query[item]), nextNotesSourceList]
    );

    const sourceCondition = {
        name,
        recruitCode,
        startApplyTime,
        endApplyTime,
        talentName,
        lastPost,
        talentSex,
        talentDegree,
        lastCompany,
        talentGraduateSchool,
        talentProfession,
        ...specialQuery
    };

    // 查询条件
    const condition = React.useMemo(
        () =>
            Object.keys(sourceCondition).reduce((ret, key) => {
                const item = sourceCondition[key];
                if (!item && item !== 0) {
                    return ret;
                }
                return { ...ret, [key]: item };
            }, {}),
        [JSON.stringify(sourceCondition)]
    );

    // 设置条件
    const setCondition = n => {
        history.push({ query: { ...query, ...n } });
    };

    // 查询
    const { data, loading, run } = useRequest(() => queryResumeList(condition), {
        refreshDeps: [condition]
    });

    // 无刷新逻辑
    const [dataSource, setDataSource] = React.useState([]);
    React.useEffect(() => {
        setDataSource(data?.data?.rows || []);
    }, [data]);

    // 页签
    const [currTab, setCurrTab] = React.useState('1');
    // 高级搜索展开标识
    const [advanceFold, setAdvanceFold] = React.useState(true);

    /**
     * 获取表单数据
     */
    const getFormCondition = React.useCallback(async () => {
        let values = {};
        try {
            values = await form.validateFields();
            const { dateRange = [], ...rest } = values;
            let startTime;
            let endTime;
            if (dateRange.length) {
                startTime = moment(dateRange[0]).format('YYYY-MM-DD 00:00:00');
                endTime = moment(dateRange[1]).format('YYYY-MM-DD 23:59:59');
            }
            values = { startApplyTime: startTime, endApplyTime: endTime, ...rest };
        } catch (error) {
            console.log(error);
        }
        return values;
    }, []);

    // 刷新
    const handleRefresh = React.useCallback(() => {
        run();
        onDataExchange();
    }, [run]);

    // 单行变更
    const handleRowChange = React.useCallback(
        (id, res) => {
            const index = dataSource.findIndex(item => item.id === id);
            if (index === -1) {
                return;
            }
            const ret = [...dataSource];
            ret.splice(index, 1, { ...dataSource[index], ...res });
            setDataSource(ret);
            onDataExchange();
        },
        [dataSource]
    );

    // 表格变化
    const handleTableChange = async (pagination, filters) => {
        const values = await getFormCondition();
        const transfer = (key, item) => {
            const arrayKeys = ['notesSourceList'];
            const next = arrayKeys.indexOf(key) === -1 ? item?.[0] || '' : item || [];
            return { [key]: next };
        };
        const con = Object.keys(filters).reduce(
            (ret, key) => {
                const item = filters[key];
                return { ...ret, ...transfer(key, item) };
            },
            { pageNo: 1 }
        );
        setCondition({ ...con, ...values });
    };
    // 跳转明细
    const handleJumpDetail = React.useCallback(
        (id, record) => {
            eventTrack({
                eventName: 'personnel_management_recruitment_demand_list_detail_resume_detail_click',
                pageName: 'personnel_management_recruitment',
                eventProps: {
                    click_context: `${recruitDetail.dutyName}-${record.talentName}`
                }
            });

            history.push({
                pathname: '/office/personnelManagement/recruitment/resume/detail',
                query: { id }
            });
        },
        [recruitDetail]
    );
    // 点击查询
    const handleSearch = async () => {
        const values = await getFormCondition();
        const newPart = { ...values, pageNo: 1 };
        if (isEqual(query, { ...query, ...newPart })) {
            run();
        } else {
            setCondition(newPart);
        }
    };
    const renderSelect = (dict, multiple) => (
        <Select
            showArrow
            allowClear
            showSearch
            optionFilterProp="children"
            mode={multiple ? 'multiple' : ''}
            maxTagCount={1}
            style={{ width: 190 }}
            placeholder="请选择"
        >
            {dict.map(item => (
                <Select.Option key={item.value} value={item.value}>
                    {item.text}
                </Select.Option>
            ))}
        </Select>
    );
    // 高阶条件
    const renderAdvanceCon = () => {
        if (advanceFold) {
            return '';
        }
        const flag = currTab === '1';
        return (
            <div className={styles.advanceCon}>
                <Form.Item label="姓名">
                    {getFieldDecorator('talentName', {
                        initialValue: talentName
                    })(<Input placeholder="请输入" allowClear style={{ width: 190 }} />)}
                </Form.Item>
                <Form.Item label="学校">
                    {getFieldDecorator('talentGraduateSchool', { initialValue: talentGraduateSchool })(
                        <Input placeholder="请输入" allowClear style={{ width: 190 }} />
                    )}
                </Form.Item>
                <Form.Item label="专业">
                    {getFieldDecorator('talentProfession', { initialValue: talentProfession })(
                        <Input placeholder="请输入" allowClear style={{ width: 190 }} />
                    )}
                </Form.Item>
                {flag && (
                    <Form.Item label="学历">
                        {getFieldDecorator('talentDegree', { initialValue: talentDegree || undefined })(
                            renderSelect(agreeTypeList)
                        )}
                    </Form.Item>
                )}
                <Form.Item label="公司">
                    {getFieldDecorator('lastCompany', { initialValue: lastCompany })(
                        <Input placeholder="请输入" allowClear style={{ width: 190 }} />
                    )}
                </Form.Item>
                <Form.Item label="行业背景">
                    {getFieldDecorator('industryTypeList', { initialValue: sourceCondition.industryTypeList })(
                        renderSelect(industryTypeDict, true)
                    )}
                </Form.Item>
                <Form.Item label="最近工作">
                    {getFieldDecorator('lastPost', { initialValue: lastPost })(
                        <Input placeholder="请输入" allowClear style={{ width: 190 }} />
                    )}
                </Form.Item>
                <Form.Item label="工作年限">
                    {getFieldDecorator('workYearTypeList', {
                        initialValue: sourceCondition.workYearTypeList || undefined
                    })(renderSelect(timeEmployedTypeList, true))}
                </Form.Item>
                {flag && (
                    <Form.Item label="性别">
                        {getFieldDecorator('talentSex', {
                            initialValue: talentSex || undefined
                        })(renderSelect(SEX))}
                    </Form.Item>
                )}
                <Form.Item label="标签">
                    <Spin spinning={tagLoading}>
                        {getFieldDecorator('recruitTagConfigIdList', {
                            initialValue: sourceCondition.recruitTagConfigIdList
                        })(
                            <Select
                                showArrow
                                allowClear
                                optionFilterProp="children"
                                style={{ width: 190 }}
                                placeholder="请选择"
                                maxTagCount={1}
                                mode="multiple"
                            >
                                {tagList?.map(item => (
                                    <Select.Option value={item.id} key={item.id}>
                                        {item.tagName}
                                    </Select.Option>
                                ))}
                            </Select>
                        )}
                    </Spin>
                </Form.Item>

                {flag && (
                    <Form.Item label="在职情况">
                        {getFieldDecorator('lastPostStatus', {
                            initialValue: sourceCondition.lastPostStatus || undefined
                        })(renderSelect(LAST_POST_STATUS))}
                    </Form.Item>
                )}
                {(isPrincipal || isLauncher) && (
                    <Form.Item label="是否已读">
                        {getFieldDecorator('readFlag', { initialValue: sourceCondition.readFlag })(
                            renderSelect(READ_FLAG)
                        )}
                    </Form.Item>
                )}
                <Form.Item label="申请时间">
                    {getFieldDecorator('dateRange', {
                        initialValue:
                            startApplyTime && endApplyTime ? [moment(startApplyTime), moment(endApplyTime)] : undefined
                    })(
                        <DatePicker.RangePicker
                            ranges={{
                                本周: [moment().startOf('week'), moment().endOf('week')],
                                本月: [moment().startOf('month'), moment().endOf('month')],
                                本季度: [moment().startOf('quarter'), moment().endOf('quarter')]
                            }}
                        />
                    )}
                </Form.Item>
            </div>
        );
    };
    // 表格
    const renderTable = () => {
        let Com;
        if (currTab === '1') {
            Com = ResumeCardTable;
        } else if (currTab === '2') {
            Com = ResumeCommonTable;
        }
        return (
            <Com
                isLauncher={isLauncher}
                isPrincipal={isPrincipal}
                onJumpDetail={handleJumpDetail}
                condition={condition}
                loading={loading}
                onRowChange={handleRowChange}
                dataSource={dataSource}
                onChange={handleTableChange}
                onRefresh={handleRefresh}
                channelDict={channelDict}
                recruitDetail={recruitDetail}
            ></Com>
        );
    };
    return (
        <>
            <Form layout="inline">
                <header className={styles.headerWrapper}>
                    <div className={styles.conditionWrapper}>
                        <Form.Item>
                            {form.getFieldDecorator('name', { initialValue: name })(
                                <CustomSearch
                                    onSearch={val => {
                                        if (!val && !query.name) return;
                                        history.replace({ query: { ...query, name: val } });
                                    }}
                                    onClick={() => {
                                        eventTrack({
                                            eventName:
                                                'personnel_management_recruitment_demand_list_detail_resume_input_click',
                                            pageName: 'personnel_management_recruitment',
                                            eventProps: {
                                                click_context: data.dutyName
                                            }
                                        });
                                    }}
                                />
                            )}
                        </Form.Item>
                        <a
                            onClick={() => {
                                eventTrack({
                                    eventName:
                                        'personnel_management_recruitment_demand_list_detail_resume_advanced_search_submit_click',
                                    pageName: 'personnel_management_recruitment',
                                    eventProps: {
                                        click_context: data.dutyName
                                    }
                                });
                                setAdvanceFold(val => !val);
                            }}
                        >
                            高级搜索
                            <Icon type={advanceFold ? 'caret-down' : 'caret-up'} />
                        </a>
                        <Button
                            type="primary"
                            style={{ marginLeft: 12 }}
                            onClick={() => {
                                eventTrack({
                                    eventName:
                                        'personnel_management_recruitment_demand_list_detail_resume_search_submit_click',
                                    pageName: 'personnel_management_recruitment',
                                    eventProps: {
                                        submit_context: form.getFieldsValue(['name'])
                                    }
                                });
                                handleSearch();
                            }}
                        >
                            搜索
                        </Button>
                    </div>
                    <div className={styles.extendWrapper}>
                        {/* <Button
                            type="primary"
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/recruitment/resume/way'
                                });
                            }}
                        >
                            渠道发布
                        </Button> */}
                        <Radio.Group defaultValue={currTab} size="middle" onChange={e => setCurrTab(e.target.value)}>
                            <Radio.Button
                                value="1"
                                onClick={() => {
                                    eventTrack({
                                        eventName:
                                            'personnel_management_recruitment_demand_list_detail_resume_list_click',
                                        pageName: 'personnel_management_recruitment',
                                        eventProps: {
                                            click_context: data.dutyName
                                        }
                                    });
                                }}
                            >
                                <i className="icon iconfont iconkuanliebiaoshitu1"></i>
                            </Radio.Button>
                            <Radio.Button
                                value="2"
                                onClick={() => {
                                    eventTrack({
                                        eventName:
                                            'personnel_management_recruitment_demand_list_detail_resume_card_click',
                                        pageName: 'personnel_management_recruitment',
                                        eventProps: {
                                            click_context: data.dutyName
                                        }
                                    });
                                }}
                            >
                                <i className="icon iconfont iconzhailiebiaoshitu1"></i>
                            </Radio.Button>
                        </Radio.Group>
                    </div>
                </header>
                {renderAdvanceCon()}
            </Form>
            {renderTable()}
            <Pagination
                current={sourceCondition.pageNo || 1}
                pageSize={sourceCondition.pageSize || 10}
                total={data?.data?.total}
                loading={loading}
                onChange={value => {
                    const { current, ...rest } = value;
                    setCondition({ ...rest, pageNo: current });
                }}
            />
        </>
    );
}

export default Form.create()(withRouter(ResumeList));
